package com.rupeng.web.controller;

import java.util.Date;
import java.util.List;
import java.util.UUID;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.http.HttpRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.rupeng.pojo.Card;
import com.rupeng.pojo.Classes;
import com.rupeng.pojo.Question;
import com.rupeng.pojo.User;
import com.rupeng.pojo.UserCard;
import com.rupeng.service.ClassesUserService;
import com.rupeng.service.QuestionService;
import com.rupeng.service.UserCardService;
import com.rupeng.service.UserService;
import com.rupeng.util.AjaxResult;
import com.rupeng.util.CommonUtils;
import com.rupeng.util.EmailUtils;
import com.rupeng.util.ImageCodeUtils;
import com.rupeng.util.SMSUtils;
import org.springframework.web.util.WebUtils;

@Controller
@RequestMapping("/user")
public class UserController {
	@Autowired
	private UserService userService;
	@Autowired
	private UserCardService userCardService;
	@Autowired
	private QuestionService questionService;
	@Autowired
	private ClassesUserService classesUserService;
	@RequestMapping(value="/register.do",method=RequestMethod.GET)
	public ModelAndView registerPage() {
		return new ModelAndView("user/register");
	}
	@RequestMapping(value="/register.do",method=RequestMethod.POST)
	public ModelAndView registerSubmit(String email, String password, String repassword, String emailCode, HttpServletRequest request) {
		ModelAndView modelAndView = new ModelAndView("user/register");
		if (CommonUtils.isEmpty(email) || CommonUtils.isEmpty(password) || CommonUtils.isEmpty(repassword) || CommonUtils.isEmpty(emailCode)) {
			modelAndView.addObject("message", "表单数据不完整");
			return modelAndView;
		} else if (!CommonUtils.isEmail(email)) {
			modelAndView.addObject("message", "邮箱格式不正确");
			return modelAndView;
		} else if (!CommonUtils.isLengthEnough(password, 6)) {
			modelAndView.addObject("message", "密码长度至少为6位");
			return modelAndView;
		} else if (!password.equals(repassword)) {
			modelAndView.addObject("message", "两次输入密码不一致");
			return modelAndView;
		}
		int result = EmailUtils.checkEmailCode(request.getSession(), email, emailCode);
		if (result==EmailUtils.CHECK_RESULT_FLASE) {
			modelAndView.addObject("message", "邮件验证码不正确");
			return modelAndView;
		} else if (result==EmailUtils.CHECK_RESULT_INVALID) {
			modelAndView.addObject("message", "邮件验证码已失效，请尝试重新获取");
			return modelAndView;
		}
		User user = new User();
		user.setEmail(email);
		if (userService.isExisted(user)) {
			modelAndView.addObject("message", "此邮箱已被注册");
			return modelAndView;
		}
		user.setCreateTime(new Date());
		String salt = ImageCodeUtils.generateCode(6);
		user.setPasswordSalt(salt);
		user.setPassword(CommonUtils.calculateMD5(salt));
		userService.insert(user);
		return new ModelAndView("user/registerSuccess");
	}
	@RequestMapping(value="/login.do",method=RequestMethod.GET)
	public ModelAndView loginPage() {
		return new ModelAndView("user/login");
	}
	@RequestMapping(value="/login.do",method=RequestMethod.POST)
	public ModelAndView loginSubmit(String loginName, String password, String imageCode, HttpServletRequest request, HttpServletResponse response) {
		ModelAndView modelAndView = new ModelAndView("user/login");
		if (!ImageCodeUtils.checkImageCode(request.getSession(), imageCode)) {
			modelAndView.addObject("message", "验证码不正确");
            return modelAndView;
		}
		if (!CommonUtils.isEmail(loginName) && !CommonUtils.isPhone(loginName)) {
			modelAndView.addObject("message", "请输入正确的邮箱或手机号");
			return modelAndView;
		}
		if (!CommonUtils.isLengthEnough(password, 6)) {
			modelAndView.addObject("message", "密码至少6位");
			return modelAndView;
		}
		User user = userService.login(loginName, password);
		if (user==null) {
			modelAndView.addObject("message", "登录名或密码错误");
			return modelAndView;
		}
		request.getSession().setAttribute("user", user);
		//添加cookie，方便自动登录
		int maxAge = 60*60*24*7; //七天
		Cookie loginNameCookie = new Cookie("loginName", loginName);
		loginNameCookie.setMaxAge(maxAge);
		loginNameCookie.setPath("/");
		response.addCookie(loginNameCookie);
		Cookie loginPasswordCookie = new Cookie("loginPassword", user.getPassword());
		loginPasswordCookie.setMaxAge(maxAge);
		loginPasswordCookie.setPath("/");
		response.addCookie(loginPasswordCookie);
		return new ModelAndView("redirect:/");
	}
	@RequestMapping("/logout.do")
	public ModelAndView logout(HttpServletRequest request, HttpServletResponse response) {
		request.getSession().invalidate();
		Cookie loginNameCookie = new Cookie("loginName", null);
		Cookie loginPasswordCookie = new Cookie("loginPassword", null);
		loginNameCookie.setMaxAge(0);
		loginNameCookie.setPath("/");
		loginPasswordCookie.setMaxAge(0);
		loginPasswordCookie.setPath("/");
		response.addCookie(loginNameCookie);
		response.addCookie(loginPasswordCookie);
		return new ModelAndView("redirect:/");
	}
	@RequestMapping("/userInfo.do")
	public ModelAndView userInfo() {
		return new ModelAndView("user/userInfo");
	}
	@RequestMapping("/updateInfo.do")
	public @ResponseBody AjaxResult updateInfo(String name, String school, Boolean isMale, HttpServletRequest request) {
		User user = (User)request.getSession().getAttribute("user");
		if (CommonUtils.isEmpty(name) || CommonUtils.isEmpty(school) || isMale==null) {
			return AjaxResult.errorInstance("提交表单信息不完整");
		}
		user = userService.selectOne(user.getId());
		user.setName(name);
		user.setSchool(school);
		user.setIsMale(isMale);
		userService.update(user);
		request.getSession().setAttribute("user", user);
		return AjaxResult.successInstance("修改信息成功");
	}
	@RequestMapping("/setPhone.do")
	public @ResponseBody AjaxResult setPhone(String phone, String smsCode, HttpServletRequest request) {
		if (CommonUtils.isEmpty(phone) || CommonUtils.isEmpty(smsCode)) {
			return AjaxResult.errorInstance("提交表单信息不完整");
		}
		User user = (User)request.getSession().getAttribute("user");
		if (!CommonUtils.isEmpty(user.getPhone())) {
			return AjaxResult.errorInstance("已绑定手机号");
		}
		int rusult = SMSUtils.checkSMSCode(request.getSession(), phone, smsCode);
		if (rusult==2) {
			return AjaxResult.errorInstance("验证码错误");
		} else if (rusult==3) {
			return AjaxResult.errorInstance("验证码过期，请重新获取");
		}
		User userPhone = new User();
		userPhone.setPhone(phone);
		if (userService.isExisted(userPhone)) {
			return AjaxResult.errorInstance("该手机已绑定其他账号");
		}
		user = userService.selectOne(user.getId());
		user.setPhone(phone);
		userService.update(user);
		request.getSession().setAttribute("user", user);
		return AjaxResult.successInstance("已绑定该手机号");
	}
	@RequestMapping(value="/passwordRetrieve.do",method=RequestMethod.GET)
	public ModelAndView passwordRetrievePage() {
		return new ModelAndView("user/passwordRetrieve");
	}
	@RequestMapping(value="/passwordRetrieve.do",method=RequestMethod.POST)
	public ModelAndView passwordRetrieveSubmit(String email, String password, String repassword, String emailCode, HttpServletRequest request) {
		ModelAndView modelAndView = new ModelAndView("user/passwordRetrieve");
		if (CommonUtils.isEmpty(email) || CommonUtils.isEmpty(password) || CommonUtils.isEmpty(repassword) || CommonUtils.isEmpty(emailCode)) {
			modelAndView.addObject("message", "表单信息不完整");
			return modelAndView;
		}
		if (!password.equals(repassword)) {
			modelAndView.addObject("message", "两次输入密码不一致");
			return modelAndView;
		}
		//检查密码长度
        if (!CommonUtils.isLengthEnough(password, 6)) {
            request.setAttribute("message", "密码至少6位");
            return modelAndView;
        }
        User user = new User();
        user.setEmail(email);
		user = userService.selectOne(user);
		if (user==null) {
			modelAndView.addObject("message", "该邮箱尚未注册");
			return modelAndView;
		}
		int result = EmailUtils.checkEmailCode(request.getSession(), email, emailCode);
		if (result==EmailUtils.CHECK_RESULT_FLASE) {
			modelAndView.addObject("message", "验证码错误");
			return modelAndView;
		} else if(result==EmailUtils.CHECK_RESULT_INVALID) {
			modelAndView.addObject("message", "验证码失效，请重新获取");
			return modelAndView;
		}
		String repasswordMd5 = CommonUtils.calculateMD5(user.getPasswordSalt()+password);
		if (repasswordMd5.equals(user.getPassword())) {
			modelAndView.addObject("message", "新密码即为旧密码！");
			return modelAndView;
		}
		user.setPassword(repasswordMd5);
		userService.update(user);
		return new ModelAndView("redirect:/user/passwordRetrieveSuccess.do");
	}
	@RequestMapping("/passwordRetrieveSuccess.do")
	public ModelAndView passwordRetrieveSuccess() {
		return new ModelAndView("user/passwordRetrieveSuccess");
	}
	@RequestMapping(value="/passwordUpdate.do",method=RequestMethod.GET)
	public ModelAndView passwordUpdatePage() {
		return new ModelAndView("user/passwordUpdate");
	}
	@RequestMapping(value="/passwordUpdate.do",method=RequestMethod.POST)
	public ModelAndView passwordUpdateSubmit(String password, String newpassword, String renewpassword, HttpServletRequest request) {
		ModelAndView modelAndView = new ModelAndView("user/passwordUpdate");
		if (CommonUtils.isEmpty(password) || CommonUtils.isEmpty(newpassword) || CommonUtils.isEmpty(renewpassword)) {
			modelAndView.addObject("message", "表单信息不完整");
			return modelAndView;
		}
		User user = (User)request.getSession().getAttribute("user");
		String passwordMd5 = CommonUtils.calculateMD5(user.getPasswordSalt()+password);
		if (!passwordMd5.equals(user.getPassword())) {
			modelAndView.addObject("message", "原密码不正确");
			return modelAndView;
		}
		if (!renewpassword.equals(newpassword)) {
			modelAndView.addObject("message", "两次输入密码不一致");
			return modelAndView;
		}
		if (password.equals(newpassword)) {
			modelAndView.addObject("message", "原密码不能与新密码相同");
			return modelAndView;
		}
		user = userService.selectOne(user.getId());
		user.setPassword(CommonUtils.calculateMD5(user.getPasswordSalt()+newpassword));
		userService.update(user);
		request.getSession().invalidate();
		return new ModelAndView("redirect:/user/login.do");
	}
	@RequestMapping("/studentHome.do")
	public ModelAndView studentHome(HttpServletRequest request) {
		User user = (User) request.getSession().getAttribute("user");
		if (user.getIsTeacher()) {
			return new ModelAndView("message", "message", "非学生身份，越权操作");
		}
		List<Classes> classes = classesUserService.selectFirstListBySecondId(user.getId());
		if (classes==null || classes.size()<1) {
            return new ModelAndView("message", "message", "您还没有加入任何班级");
        }
		ModelAndView modelAndView = new ModelAndView("user/studentHome");
		List<Card> cards = userCardService.selectSecondListByFirstId(user.getId());
		modelAndView.addObject("cards", cards);
		List<Question> questions = questionService.selectUnresolvedQuestionByStudentId(user.getId());
		modelAndView.addObject("questions", questions);
		return modelAndView;
	}
	@RequestMapping("/teacherHome.do")
	public ModelAndView teacherHome(HttpServletRequest request) {
		User user = (User) request.getSession().getAttribute("user");
		if (!user.getIsTeacher()) {
			return new ModelAndView("message", "message", "非教师身份，越权操作");
		}
		ModelAndView modelAndView = new ModelAndView("user/teacherHome");
		List<Question> questions = questionService.selectUnresolvedQuestionByTeacherId(user.getId());
		modelAndView.addObject("questions", questions);
		return modelAndView;
	}
	
}
